package com.hsy.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hsy.service.UserService;
import com.hsy.service.impl.UserServiceImpl;
import com.hsy.pojo.User;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/GetUserInfoServlet")
public class GetUserInfoServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取前端传递的 userId
        Long userId = Long.valueOf(request.getParameter("userId"));

        response.setCharacterEncoding("UTF-8"); // 防止post请求乱码，设置请求的参数字符集为UTf-8
        response.setContentType("application/json;charset=UTF-8");  // // 设置响应头，指定返回数据的格式为JSON以及字符编码

        // 获取用户信息
        User user = userService.selectUserByUserId(userId);

        // 检查用户是否存在
        if (user != null) {
            // 将用户信息转化为 JSON 字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String responseJson = objectMapper.writeValueAsString(user);

            // 获取响应输出流并写入 JSON 数据
            PrintWriter writer = response.getWriter();
            writer.write(responseJson);
            writer.flush();
            writer.close();
        } else {
            // 如果没有找到用户信息，返回错误信息
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.getWriter().write("{\"message\": \"User not found\"}");
        }
    }

}
